import { ref, computed, watch, onMounted } from 'vue'

/**
 * 主题背景色管理 Hook
 * 
 * @param {string} defaultTheme - 默认主题色
 * @param {Object} options - 配置选项
 * @param {string} options.storage - 存储类型 ('localStorage' | 'sessionStorage')
 * @param {string} options.storageKey - 存储键名
 * @param {boolean} options.autoApply - 是否自动应用到CSS变量
 * @param {string} options.cssVarPrefix - CSS变量前缀
 * @returns {Object} 主题管理对象
 */
export function useTheme(defaultTheme = '#ffffff', options = {}) {
    const {
        storage = 'localStorage',
        storageKey = 'app-theme',
        autoApply = true,
        cssVarPrefix = '--app'
    } = options

    // 预设主题色
    const presetThemes = {
        light: '#ffffff',
        dark: '#1a1a1a',
        blue: '#f0f8ff',
        green: '#f0fff0',
        pink: '#fff0f5',
        orange: '#fff8f0',
        purple: '#f8f0ff',
        red: '#fff0f0',
        yellow: '#fffff0',
        cyan: '#f0ffff',
        gray: '#f5f5f5'
    }

    // 当前主题色
    const currentTheme = ref(defaultTheme)
    
    // 主题历史记录
    const themeHistory = ref([])
    
    // 是否正在加载
    const loading = ref(false)

    // 获取存储的主题色
    const getStoredTheme = () => {
        try {
            if (storage === 'localStorage') {
                return localStorage.getItem(storageKey)
            } else if (storage === 'sessionStorage') {
                return sessionStorage.getItem(storageKey)
            }
        } catch (error) {
            console.warn('无法访问存储:', error)
        }
        return null
    }

    // 保存主题色到存储
    const saveTheme = (theme) => {
        try {
            if (storage === 'localStorage') {
                localStorage.setItem(storageKey, theme)
            } else if (storage === 'sessionStorage') {
                sessionStorage.setItem(storageKey, theme)
            }
        } catch (error) {
            console.warn('无法保存到存储:', error)
        }
    }

    // 应用主题色到CSS变量
    const applyTheme = (theme) => {
        if (!autoApply) return
        
        const root = document.documentElement
        const body = document.body
        
        // 设置主要CSS变量
        root.style.setProperty(`${cssVarPrefix}-bg-color`, theme)
        root.style.setProperty(`${cssVarPrefix}-bg-color-rgb`, hexToRgb(theme))
        
        // 设置demo主题变量（用于HooksDemo页面）
        root.style.setProperty('--demo-bg-color', theme)
        root.style.setProperty('--demo-bg-color-rgb', hexToRgb(theme))
        
        // 计算对比色（用于文字等）
        const contrastColor = getContrastColor(theme)
        root.style.setProperty(`${cssVarPrefix}-text-color`, contrastColor)
        root.style.setProperty('--demo-text-color', contrastColor)
        
        // 直接设置body和html的背景色
        body.style.backgroundColor = theme
        document.documentElement.style.backgroundColor = theme
        
        // 设置#app的背景色
        const appElement = document.getElementById('app')
        if (appElement) {
            appElement.style.backgroundColor = theme
        }
        
        // 设置所有主要页面的背景色
        const pageElements = document.querySelectorAll('.hooks-demo, .home, .about, .canves, .element-css, .home-page, .system-page, .page-content, .content-area, .main-content')
        pageElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有卡片的背景色
        const cardElements = document.querySelectorAll('.el-card, .my-el-card')
        cardElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有表格的背景色
        const tableElements = document.querySelectorAll('.el-table, .el-table th, .el-table td')
        tableElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有对话框的背景色
        const dialogElements = document.querySelectorAll('.el-dialog')
        dialogElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有下拉菜单的背景色
        const dropdownElements = document.querySelectorAll('.el-dropdown-menu, .el-select-dropdown, .el-date-picker, .el-time-picker, .el-cascader__dropdown')
        dropdownElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有弹出框的背景色
        const popoverElements = document.querySelectorAll('.el-popover, .el-popconfirm, .el-tooltip__popper')
        popoverElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有消息提示的背景色
        const messageElements = document.querySelectorAll('.el-message, .el-notification')
        messageElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有加载遮罩的背景色
        const loadingElements = document.querySelectorAll('.el-loading-mask')
        loadingElements.forEach(element => {
            element.style.backgroundColor = `rgba(${hexToRgb(theme)}, 0.8)`
        })
        
        // 设置所有标签的背景色
        const tagElements = document.querySelectorAll('.el-tag')
        tagElements.forEach(element => {
            element.style.backgroundColor = `rgba(${hexToRgb(theme)}, 0.1)`
            element.style.borderColor = `rgba(${hexToRgb(theme)}, 0.2)`
        })
        
        // 设置所有分割线的背景色
        const dividerElements = document.querySelectorAll('.el-divider')
        dividerElements.forEach(element => {
            element.style.backgroundColor = `rgba(${hexToRgb(theme)}, 0.2)`
        })
        
        // 设置所有回到顶部按钮的背景色
        const backtopElements = document.querySelectorAll('.el-backtop')
        backtopElements.forEach(element => {
            element.style.backgroundColor = `rgba(${hexToRgb(theme)}, 0.8)`
        })
        
        // 设置所有虚拟滚动条的背景色
        const scrollbarElements = document.querySelectorAll('.el-virtual-scrollbar')
        scrollbarElements.forEach(element => {
            element.style.backgroundColor = `rgba(${hexToRgb(theme)}, 0.1)`
        })
        
        // 设置所有折叠面板的背景色
        const collapseElements = document.querySelectorAll('.el-collapse-item__header, .el-collapse-item__content, .el-collapse-item__wrap')
        collapseElements.forEach(element => {
            if (element.classList.contains('el-collapse-item__header')) {
                element.style.backgroundColor = `rgba(${hexToRgb(theme)}, 0.05)`
            } else {
                element.style.backgroundColor = theme
            }
        })
        
        // 设置所有抽屉的背景色
        const drawerElements = document.querySelectorAll('.el-drawer')
        drawerElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有描述列表的背景色
        const descriptionsElements = document.querySelectorAll('.el-descriptions__body')
        descriptionsElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有标签页内容的背景色
        const tabsElements = document.querySelectorAll('.el-tabs__content')
        tabsElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有步骤条内容的背景色
        const stepsElements = document.querySelectorAll('.el-steps')
        stepsElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有时间线内容的背景色
        const timelineElements = document.querySelectorAll('.el-timeline')
        timelineElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有轮播图内容的背景色
        const carouselElements = document.querySelectorAll('.el-carousel')
        carouselElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有空状态内容的背景色
        const emptyElements = document.querySelectorAll('.el-empty')
        emptyElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有骨架屏内容的背景色
        const skeletonElements = document.querySelectorAll('.el-skeleton')
        skeletonElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有结果内容的背景色
        const resultElements = document.querySelectorAll('.el-result')
        resultElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有统计数值内容的背景色
        const statisticElements = document.querySelectorAll('.el-statistic')
        statisticElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有头像内容的背景色
        const avatarElements = document.querySelectorAll('.el-avatar')
        avatarElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有图片内容的背景色
        const imageElements = document.querySelectorAll('.el-image')
        imageElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有链接内容的背景色
        const linkElements = document.querySelectorAll('.el-link')
        linkElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有无限滚动内容的背景色
        const infiniteElements = document.querySelectorAll('.el-infinite-scroll')
        infiniteElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有页面相关元素的背景色
        const pageRelatedElements = document.querySelectorAll('[class*="page"], [class*="Page"], [class*="view"], [class*="View"], [class*="content"], [class*="Content"], [class*="main"], [class*="Main"], [class*="container"], [class*="Container"], [class*="wrapper"], [class*="Wrapper"]')
        pageRelatedElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 设置所有导航相关元素的背景色
        const navElements = document.querySelectorAll('nav, [class*="nav"], [class*="Nav"], [class*="menu"], [class*="Menu"], [class*="sidebar"], [class*="Sidebar"], [class*="aside"], [class*="Aside"], [class*="header"], [class*="Header"], [class*="top"], [class*="Top"], [class*="footer"], [class*="Footer"], [class*="bottom"], [class*="Bottom"]')
        navElements.forEach(element => {
            element.style.backgroundColor = `rgba(${hexToRgb(theme)}, 0.9)`
        })
        
        // 设置所有表单相关元素的背景色
        const formElements = document.querySelectorAll('input, textarea, select, [class*="input"], [class*="Input"], [class*="form"], [class*="Form"]')
        formElements.forEach(element => {
            if (element.type !== 'color') {
                element.style.backgroundColor = `rgba(${hexToRgb(theme)}, 0.05)`
                element.style.borderColor = `rgba(${hexToRgb(theme)}, 0.2)`
            }
        })
        
        // 设置所有按钮元素的过渡效果
        const buttonElements = document.querySelectorAll('button, [class*="button"], [class*="Button"]')
        buttonElements.forEach(element => {
            element.style.transition = 'all 0.3s ease'
        })
        
        // 设置所有通用容器的背景色
        const genericElements = document.querySelectorAll('[class*="card"], [class*="Card"], [class*="panel"], [class*="Panel"], [class*="section"], [class*="Section"], [class*="block"], [class*="Block"], [class*="area"], [class*="Area"], [class*="zone"], [class*="Zone"]')
        genericElements.forEach(element => {
            element.style.backgroundColor = theme
        })
        
        // 延迟执行，确保动态元素也被应用主题色
        setTimeout(() => {
            // 重新应用主题色，覆盖可能遗漏的元素
            const allElements = document.querySelectorAll('*')
            allElements.forEach(element => {
                if (element.style && element.style.backgroundColor && 
                    (element.style.backgroundColor === 'rgb(255, 255, 255)' || 
                     element.style.backgroundColor === '#ffffff' ||
                     element.style.backgroundColor === 'white')) {
                    element.style.backgroundColor = theme
                }
            })
        }, 100)
        
        console.log(`主题已应用到所有元素: ${theme}`)
    }

    // 十六进制转RGB
    const hexToRgb = (hex) => {
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
        if (result) {
            const r = parseInt(result[1], 16)
            const g = parseInt(result[2], 16)
            const b = parseInt(result[3], 16)
            return `${r}, ${g}, ${b}`
        }
        return '255, 255, 255'
    }

    // 获取对比色
    const getContrastColor = (hex) => {
        const rgb = hexToRgb(hex).split(', ').map(Number)
        const brightness = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000
        return brightness > 128 ? '#000000' : '#ffffff'
    }

    // 设置主题色
    /**
     * 设置主题函数
     * @param {string} theme - 要设置的主题名称
     */
    const setTheme = (theme) => {
        // 如果设置的主题与当前主题相同，则直接返回
        if (theme === currentTheme.value) return
        
        // 设置加载状态为true
        loading.value = true
        
        // 添加到历史记录
        if (themeHistory.value.length >= 10) {
            themeHistory.value.shift()
        }
        themeHistory.value.push(currentTheme.value)
        
        currentTheme.value = theme
        saveTheme(theme)
        applyTheme(theme)
        
        loading.value = false
    }

    // 设置预设主题
/**
 * 设置预设主题
 * @param {string} themeName - 主题名称
 */
    const setPresetTheme = (themeName) => {
    // 检查预设主题中是否存在指定名称的主题
        if (presetThemes[themeName]) {
        // 如果存在，则设置该主题
            setTheme(presetThemes[themeName])
        }
    }

    // 随机主题色
    const setRandomTheme = () => {
        const colors = [
            '#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57',
            '#ff9ff3', '#54a0ff', '#5f27cd', '#00d2d3', '#ff9f43',
            '#ff7675', '#74b9ff', '#fd79a8', '#fdcb6e', '#6c5ce7',
            '#a29bfe', '#fd79a8', '#fdcb6e', '#6c5ce7', '#a29bfe'
        ]
        const randomColor = colors[Math.floor(Math.random() * colors.length)]
        setTheme(randomColor)
    }

    // 重置主题色
    const resetTheme = () => {
        setTheme(defaultTheme)
    }

    // 恢复上一个主题色
    const undoTheme = () => {
        if (themeHistory.value.length > 0) {
            const previousTheme = themeHistory.value.pop()
            setTheme(previousTheme)
        }
    }

    // 清除历史记录
    const clearHistory = () => {
        themeHistory.value = []
    }

    // 计算属性
    const isDark = computed(() => {
        const rgb = hexToRgb(currentTheme.value).split(', ').map(Number)
        const brightness = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000
        return brightness < 128
    })

    const isLight = computed(() => !isDark.value)

    const themeInfo = computed(() => ({
        color: currentTheme.value,
        rgb: hexToRgb(currentTheme.value),
        isDark: isDark.value,
        isLight: isLight.value,
        contrastColor: getContrastColor(currentTheme.value)
    }))

    // 监听主题色变化
    watch(currentTheme, (newTheme) => {
        applyTheme(newTheme)
    })

    // 组件挂载时初始化
    onMounted(() => {
        const storedTheme = getStoredTheme()
        if (storedTheme) {
            currentTheme.value = storedTheme
        }
        applyTheme(currentTheme.value)
    })

    return {
        // 状态
        currentTheme: computed(() => currentTheme.value),
        loading: computed(() => loading.value),
        themeHistory: computed(() => themeHistory.value),
        
        // 计算属性
        isDark,
        isLight,
        themeInfo,
        
        // 方法
        setTheme,
        setPresetTheme,
        setRandomTheme,
        resetTheme,
        undoTheme,
        clearHistory,
        
        // 预设主题
        presetThemes
    }
} 